package com.hup.joystick.model;

import com.hup.joystick.constant.DeviceKey.KeyType;
import com.hup.joystick.constant.DeviceKey.StandardKeys;
import com.hup.joystick.model.joystick.NativeKey;
import com.hup.joystick.model.joystick.StandardKey;
import com.hup.joystick.service.jna.DIJoyState2;
import com.hup.joystick.view.joySetting.KeyBindingItem;
import com.hup.utils.commons.TextUtil;
import lombok.Data;

import java.util.HashMap;

/**
 * 标准按键-原始按键的映射关系类;
 * 自定义按键只映射到 {@link #buttonMap}
 *
 * @author hugan
 * @date 2020/10/23
 */
@Data
public class KeyMapConfig {

    public static final int NULL_ARROW_INDEX = -1;
    /**
     * [key=标准按钮,value=原始按钮]
     * [A,按钮8]
     * [B,Z轴+]
     * [自义定按钮,按钮88]
     * key是唯一的;
     * value非空时是唯一的
     */
    public HashMap<String, String> buttonMap = new HashMap<>();
    /**
     * 标准方向键是 {@link DIJoyState2#rgdwPOV}的哪个index
     */
    public int arrowIndex = NULL_ARROW_INDEX;
    /**
     * 左摇杆X的原始轴名,如:RZ轴
     */
    public String stickLX;
    /**
     * 左摇杆Y
     */
    public String stickLY;
    /**
     * 右摇杆X
     */
    public String stickRX;
    /**
     * 右摇杆Y
     */
    public String stickRY;

    public void reset() {
        buttonMap.clear();
        arrowIndex = NULL_ARROW_INDEX;
        stickLX = null;
        stickLY = null;
        stickRX = null;
        stickRY = null;
    }

    /**
     * 将界面内容转化成配置属性;
     * 调用前需要 {@link #reset()}
     */
    public void viewToConfig(KeyBindingItem item) {
        StandardKey standardKey = item.getStandardKey();
        NativeKey nativeKey = item.getNativeKey();
        boolean noneNativeKey = nativeKey == null || TextUtil.isBlank(nativeKey.key);

        if (standardKey.type == KeyType.BTN) {
            //格式在字段注解中
            buttonMap.put(standardKey.key, noneNativeKey ? null : nativeKey.key);
        } else if (standardKey.type == KeyType.STICK) {
            //去掉nativeKey末尾的正负号
            String stickStr;
            if (noneNativeKey) {
                stickStr = null;
            } else {
                stickStr = nativeKey.key.substring(0, nativeKey.key.length() - 1);
            }
            if (standardKey.equals(StandardKeys.BINDING_STICK_LX)) {
                stickLX = stickStr;
            } else if (standardKey.equals(StandardKeys.BINDING_STICK_LY)) {
                stickLY = stickStr;
            } else if (standardKey.equals(StandardKeys.BINDING_STICK_RX)) {
                stickRX = stickStr;
            } else if (standardKey.equals(StandardKeys.BINDING_STICK_RY)) {
                stickRY = stickStr;
            }
        } else if (standardKey.type == KeyType.ARROW) {
            if (noneNativeKey) {
                arrowIndex = NULL_ARROW_INDEX;
            } else {
                String key = nativeKey.key;//如:1左上
                arrowIndex = Integer.parseInt(String.valueOf(key.charAt(0)));
            }
        }
    }

}
